import { defineStore } from 'pinia'
import { login, getUserInfo } from '@/api/user'

export const useUserStore = defineStore({
  id: 'user', // id必填，且需要唯一
  state: () => ({
    token: uni.getStorageSync('token') || '',
    userInfo: null,
    isLogin: false
  }),

  actions: {
    // 微信登录
    async wxLogin(code, phone) {
      try {
        const data = await login({ code, phone })
        this.token = data.token
        this.userInfo = data.user_info
        this.isLogin = true
        uni.setStorageSync('token', data.token)
        return data
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getInfo() {
      try {
        const data = await getUserInfo()
        this.userInfo = data
        this.isLogin = true
        return data
      } catch (error) {
        throw error
      }
    },

    // 退出登录
    logout() {
      this.token = ''
      this.userInfo = null
      this.isLogin = false
      uni.removeStorageSync('token')
    }
  }
}) 